package controllers

import (
	"encoding/json"
	"errors"
	"time"

	md "gitee.com/countpoison/youbei/models"
	"gitee.com/countpoison/youbei/utils"
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/httplib"
	jwt "github.com/dgrijalva/jwt-go"
)

//Userlogin ...
func (c *LoginController) Userlogin() {
	name := c.Ctx.Input.Param(":name")
	password := c.Ctx.Input.Param(":password")
	userinfo, err := md.UserLogin(name, password)
	c.APIReturn(500, "登陆失败", err)
	if c.Ctx.Input.IP() == "::1" {
		goto Access
	}
	if len(userinfo.IPlist) > 0 {
		for _, v := range userinfo.IPlist {
			if v == c.Ctx.Input.IP() {
				goto Access
			}
		}
		c.APIReturn(401, "不允许从当前ip登录", errors.New("不允许从当前ip登录"))
	}
Access:
	claims := make(jwt.MapClaims)
	claims["exp"] = time.Now().Add(time.Hour * time.Duration(1)).Unix()
	claims["iat"] = time.Now().Unix()
	claims["username"] = name
	claims["userid"] = userinfo.ID
	claims["User"] = "true"
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	tokenString, err := token.SignedString([]byte(beego.AppConfig.String("jwtkey")))
	c.APIReturn(500, "token生成失败", err)
	c.APIReturn(200, "登陆成功", tokenString)
}

//Userchangepwd ...
func (c *MainController) Userchangepwd() {
	opassword := c.GetString("opwd")
	password := c.GetString("npwd")
	userid := c.Ctx.Input.Param(":id")
	c.APIReturn(500, "修改失败", md.UserChangePwd(userid, opassword, password))
	c.APIReturn(200, "修改成功", nil)
}

//Prepare ...
func (c *MainController) Prepare() {
	tokenHeader := c.Ctx.Input.Header("token")
	if tokenHeader == "" {
		c.APIReturn(401, "token不能为空", errors.New("token不能为空"))
	}
	claims := make(jwt.MapClaims)
	token, err := jwt.ParseWithClaims(tokenHeader, claims, func(token *jwt.Token) (interface{}, error) {
		return []byte(beego.AppConfig.String("jwtkey")), nil
	})
	c.APIReturn(401, "验证失败", err)
	if !token.Valid {
		c.APIReturn(401, "验证失败", errors.New("验证失败"))
	}

}

//UserList ...
func (c *MainController) UserList() {
	limit, _ := c.GetInt("count")
	page, _ := c.GetInt("page")
	users := make([]md.User, 0)
	var err error
	if limit <= 0 {
		err = md.Localdb().Desc("created").Limit(limit, limit*(page-1)).Find(&users)
	} else {
		err = md.Localdb().Desc("created").Find(&users)
	}
	c.APIReturn(500, "获取列表失败", err)
	count, err := md.Localdb().Count(new(md.User))
	c.APIReturn(500, "获取用户总数失败", err)
	rep := map[string]interface{}{"count": count, "data": users}
	c.APIReturn(200, "获取用户列表成功", &rep)
}

//GetUser ...
func (c *MainController) GetUser() {
	id := c.Ctx.Input.Param(":id")
	user := new(md.User)
	user.ID = id
	bol, err := md.Localdb().Get(user)
	c.APIReturn(500, "获取用户失败", err)
	if !bol {
		c.APIReturn(500, "获取用户失败", errors.New("user not found"))
	}

	c.APIReturn(200, "获取用户成功", user)
}

//AddUser ...
func (c *MainController) AddUser() {
	ob := new(md.User)
	c.APIReturn(500, "解析数据失败", json.Unmarshal(c.Ctx.Input.RequestBody, ob))
	c.APIReturn(500, "添加用户失败", ob.Add())
	c.APIReturn(200, "成功", nil)
}

//EditUser ...
func (c *MainController) EditUser() {
	ob := new(md.User)
	c.APIReturn(500, "解析数据失败", json.Unmarshal(c.Ctx.Input.RequestBody, ob))
	c.APIReturn(500, "修改用户失败", ob.Update())
	c.APIReturn(200, "成功", nil)
}

//DeleteUser ...
func (c *MainController) DeleteUser() {
	id := c.Ctx.Input.Param(":id")
	c.APIReturn(500, "删除用户失败", md.DeleteUser(id))
	c.APIReturn(200, "删除用户成功", nil)
}

func (c *MainController) ConnectHost() {
	id := c.Ctx.Input.Param(":id")
	host := new(md.Host)
	bol, err := md.Localdb().ID(id).Get(host)
	c.APIReturn(500, "获取信息失败", err)
	if !bol {
		c.APIReturn(500, "信息不存在", errors.New("信息不存在"))
	}
	url := host.Protocol + "://" + host.HostAddr + ":" + host.Port
	req := httplib.Get(url + "/api/login/" + host.Username + "/" + utils.Md5V(host.Password))
	resapi := ResAPI{}
	c.APIReturn(500, "登录失败21", req.ToJSON(&resapi))
	if resapi.Success != 200 {
		c.APIReturn(500, "登录失败2", errors.New(resapi.Msg))
	}
	c.APIReturn(200, "登录成功", resapi.Result)
}
